home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / perl5 / Encode.pm < prev    next >
Encoding:
Perl POD Document  |  2011-08-09  |  31.9 KB  |  1,005 lines

  1. #
  2. # $Id: Encode.pm,v 2.44 2011/08/09 07:49:44 dankogai Exp dankogai $
  3. #
  4. package Encode;
  5. use strict;
  6. use warnings;
  7. our $VERSION = sprintf "%d.%02d", q$Revision: 2.44 $ =~ /(\d+)/g;
  8. use constant DEBUG => !!$ENV{PERL_ENCODE_DEBUG};
  9. use XSLoader ();
  10. XSLoader::load( __PACKAGE__, $VERSION );
  11.  
  12. require Exporter;
  13. use base qw/Exporter/;
  14.  
  15. # Public, encouraged API is exported by default
  16.  
  17. our @EXPORT = qw(
  18.   decode  decode_utf8  encode  encode_utf8 str2bytes bytes2str
  19.   encodings  find_encoding clone_encoding
  20. );
  21. our @FB_FLAGS = qw(
  22.   DIE_ON_ERR WARN_ON_ERR RETURN_ON_ERR LEAVE_SRC
  23.   PERLQQ HTMLCREF XMLCREF STOP_AT_PARTIAL
  24. );
  25. our @FB_CONSTS = qw(
  26.   FB_DEFAULT FB_CROAK FB_QUIET FB_WARN
  27.   FB_PERLQQ FB_HTMLCREF FB_XMLCREF
  28. );
  29. our @EXPORT_OK = (
  30.     qw(
  31.       _utf8_off _utf8_on define_encoding from_to is_16bit is_8bit
  32.       is_utf8 perlio_ok resolve_alias utf8_downgrade utf8_upgrade
  33.       ),
  34.     @FB_FLAGS, @FB_CONSTS,
  35. );
  36.  
  37. our %EXPORT_TAGS = (
  38.     all          => [ @EXPORT,    @EXPORT_OK ],
  39.     default      => [ @EXPORT ],
  40.     fallbacks    => [ @FB_CONSTS ],
  41.     fallback_all => [ @FB_CONSTS, @FB_FLAGS ],
  42. );
  43.  
  44. # Documentation moved after __END__ for speed - NI-S
  45.  
  46. our $ON_EBCDIC = ( ord("A") == 193 );
  47.  
  48. use Encode::Alias;
  49.  
  50. # Make a %Encoding package variable to allow a certain amount of cheating
  51. our %Encoding;
  52. our %ExtModule;
  53. require Encode::Config;
  54. #  See
  55. #  https://bugzilla.redhat.com/show_bug.cgi?id=435505#c2
  56. #  to find why sig handers inside eval{} are disabled.
  57. eval {
  58.     local $SIG{__DIE__};
  59.     local $SIG{__WARN__};
  60.     require Encode::ConfigLocal;
  61. };
  62.  
  63. sub encodings {
  64.     my $class = shift;
  65.     my %enc;
  66.     if ( @_ and $_[0] eq ":all" ) {
  67.         %enc = ( %Encoding, %ExtModule );
  68.     }
  69.     else {
  70.         %enc = %Encoding;
  71.         for my $mod ( map { m/::/ ? $_ : "Encode::$_" } @_ ) {
  72.             DEBUG and warn $mod;
  73.             for my $enc ( keys %ExtModule ) {
  74.                 $ExtModule{$enc} eq $mod and $enc{$enc} = $mod;
  75.             }
  76.         }
  77.     }
  78.     return sort { lc $a cmp lc $b }
  79.       grep      { !/^(?:Internal|Unicode|Guess)$/o } keys %enc;
  80. }
  81.  
  82. sub perlio_ok {
  83.     my $obj = ref( $_[0] ) ? $_[0] : find_encoding( $_[0] );
  84.     $obj->can("perlio_ok") and return $obj->perlio_ok();
  85.     return 0;    # safety net
  86. }
  87.  
  88. sub define_encoding {
  89.     my $obj  = shift;
  90.     my $name = shift;
  91.     $Encoding{$name} = $obj;
  92.     my $lc = lc($name);
  93.     define_alias( $lc => $obj ) unless $lc eq $name;
  94.     while (@_) {
  95.         my $alias = shift;
  96.         define_alias( $alias, $obj );
  97.     }
  98.     return $obj;
  99. }
  100.  
  101. sub getEncoding {
  102.     my ( $class, $name, $skip_external ) = @_;
  103.  
  104.     $name =~ s/\s+//g; # https://rt.cpan.org/Ticket/Display.html?id=65796
  105.  
  106.     ref($name) && $name->can('renew') and return $name;
  107.     exists $Encoding{$name} and return $Encoding{$name};
  108.     my $lc = lc $name;
  109.     exists $Encoding{$lc} and return $Encoding{$lc};
  110.  
  111.     my $oc = $class->find_alias($name);
  112.     defined($oc) and return $oc;
  113.     $lc ne $name and $oc = $class->find_alias($lc);
  114.     defined($oc) and return $oc;
  115.  
  116.     unless ($skip_external) {
  117.         if ( my $mod = $ExtModule{$name} || $ExtModule{$lc} ) {
  118.             $mod =~ s,::,/,g;
  119.             $mod .= '.pm';
  120.             eval { require $mod; };
  121.             exists $Encoding{$name} and return $Encoding{$name};
  122.         }
  123.     }
  124.     return;
  125. }
  126.  
  127. sub find_encoding($;$) {
  128.     my ( $name, $skip_external ) = @_;
  129.     return __PACKAGE__->getEncoding( $name, $skip_external );
  130. }
  131.  
  132. sub resolve_alias($) {
  133.     my $obj = find_encoding(shift);
  134.     defined $obj and return $obj->name;
  135.     return;
  136. }
  137.  
  138. sub clone_encoding($) {
  139.     my $obj = find_encoding(shift);
  140.     ref $obj or return;
  141.     eval { require Storable };
  142.     $@ and return;
  143.     return Storable::dclone($obj);
  144. }
  145.  
  146. sub encode($$;$) {
  147.     my ( $name, $string, $check ) = @_;
  148.     return undef unless defined $string;
  149.     $string .= '' if ref $string;    # stringify;
  150.     $check ||= 0;
  151.     unless ( defined $name ) {
  152.         require Carp;
  153.         Carp::croak("Encoding name should not be undef");
  154.     }
  155.     my $enc = find_encoding($name);
  156.     unless ( defined $enc ) {
  157.         require Carp;
  158.         Carp::croak("Unknown encoding '$name'");
  159.     }
  160.     my $octets = $enc->encode( $string, $check );
  161.     $_[1] = $string if $check and !ref $check and !( $check & LEAVE_SRC() );
  162.     return $octets;
  163. }
  164. *str2bytes = \&encode;
  165.  
  166. sub decode($$;$) {
  167.     my ( $name, $octets, $check ) = @_;
  168.     return undef unless defined $octets;
  169.     $octets .= '' if ref $octets;
  170.     $check ||= 0;
  171.     my $enc = find_encoding($name);
  172.     unless ( defined $enc ) {
  173.         require Carp;
  174.         Carp::croak("Unknown encoding '$name'");
  175.     }
  176.     my $string = $enc->decode( $octets, $check );
  177.     $_[1] = $octets if $check and !ref $check and !( $check & LEAVE_SRC() );
  178.     return $string;
  179. }
  180. *bytes2str = \&decode;
  181.  
  182. sub from_to($$$;$) {
  183.     my ( $string, $from, $to, $check ) = @_;
  184.     return undef unless defined $string;
  185.     $check ||= 0;
  186.     my $f = find_encoding($from);
  187.     unless ( defined $f ) {
  188.         require Carp;
  189.         Carp::croak("Unknown encoding '$from'");
  190.     }
  191.     my $t = find_encoding($to);
  192.     unless ( defined $t ) {
  193.         require Carp;
  194.         Carp::croak("Unknown encoding '$to'");
  195.     }
  196.     my $uni = $f->decode($string);
  197.     $_[0] = $string = $t->encode( $uni, $check );
  198.     return undef if ( $check && length($uni) );
  199.     return defined( $_[0] ) ? length($string) : undef;
  200. }
  201.  
  202. sub encode_utf8($) {
  203.     my ($str) = @_;
  204.     utf8::encode($str);
  205.     return $str;
  206. }
  207.  
  208. my $utf8enc;
  209.  
  210. sub decode_utf8($;$) {
  211.     my ( $octets, $check ) = @_;
  212.     return $octets if is_utf8($octets);
  213.     return undef unless defined $octets;
  214.     $octets .= '' if ref $octets;
  215.     $check   ||= 0;
  216.     $utf8enc ||= find_encoding('utf8');
  217.     my $string = $utf8enc->decode( $octets, $check );
  218.     $_[0] = $octets if $check and !ref $check and !( $check & LEAVE_SRC() );
  219.     return $string;
  220. }
  221.  
  222. # sub decode_utf8($;$) {
  223. #     my ( $str, $check ) = @_;
  224. #     return $str if is_utf8($str);
  225. #     if ($check) {
  226. #         return decode( "utf8", $str, $check );
  227. #     }
  228. #     else {
  229. #         return decode( "utf8", $str );
  230. #         return $str;
  231. #     }
  232. # }
  233.  
  234. predefine_encodings(1);
  235.  
  236. #
  237. # This is to restore %Encoding if really needed;
  238. #
  239.  
  240. sub predefine_encodings {
  241.     require Encode::Encoding;
  242.     no warnings 'redefine';
  243.     my $use_xs = shift;
  244.     if ($ON_EBCDIC) {
  245.  
  246.         # was in Encode::UTF_EBCDIC
  247.         package Encode::UTF_EBCDIC;
  248.         push @Encode::UTF_EBCDIC::ISA, 'Encode::Encoding';
  249.         *decode = sub {
  250.             my ( $obj, $str, $chk ) = @_;
  251.             my $res = '';
  252.             for ( my $i = 0 ; $i < length($str) ; $i++ ) {
  253.                 $res .=
  254.                   chr(
  255.                     utf8::unicode_to_native( ord( substr( $str, $i, 1 ) ) )
  256.                   );
  257.             }
  258.             $_[1] = '' if $chk;
  259.             return $res;
  260.         };
  261.         *encode = sub {
  262.             my ( $obj, $str, $chk ) = @_;
  263.             my $res = '';
  264.             for ( my $i = 0 ; $i < length($str) ; $i++ ) {
  265.                 $res .=
  266.                   chr(
  267.                     utf8::native_to_unicode( ord( substr( $str, $i, 1 ) ) )
  268.                   );
  269.             }
  270.             $_[1] = '' if $chk;
  271.             return $res;
  272.         };
  273.         $Encode::Encoding{Unicode} =
  274.           bless { Name => "UTF_EBCDIC" } => "Encode::UTF_EBCDIC";
  275.     }
  276.     else {
  277.  
  278.         package Encode::Internal;
  279.         push @Encode::Internal::ISA, 'Encode::Encoding';
  280.         *decode = sub {
  281.             my ( $obj, $str, $chk ) = @_;
  282.             utf8::upgrade($str);
  283.             $_[1] = '' if $chk;
  284.             return $str;
  285.         };
  286.         *encode = \&decode;
  287.         $Encode::Encoding{Unicode} =
  288.           bless { Name => "Internal" } => "Encode::Internal";
  289.     }
  290.  
  291.     {
  292.  
  293.         # was in Encode::utf8
  294.         package Encode::utf8;
  295.         push @Encode::utf8::ISA, 'Encode::Encoding';
  296.  
  297.         #
  298.         if ($use_xs) {
  299.             Encode::DEBUG and warn __PACKAGE__, " XS on";
  300.             *decode = \&decode_xs;
  301.             *encode = \&encode_xs;
  302.         }
  303.         else {
  304.             Encode::DEBUG and warn __PACKAGE__, " XS off";
  305.             *decode = sub {
  306.                 my ( $obj, $octets, $chk ) = @_;
  307.                 my $str = Encode::decode_utf8($octets);
  308.                 if ( defined $str ) {
  309.                     $_[1] = '' if $chk;
  310.                     return $str;
  311.                 }
  312.                 return undef;
  313.             };
  314.             *encode = sub {
  315.                 my ( $obj, $string, $chk ) = @_;
  316.                 my $octets = Encode::encode_utf8($string);
  317.                 $_[1] = '' if $chk;
  318.                 return $octets;
  319.             };
  320.         }
  321.         *cat_decode = sub {    # ($obj, $dst, $src, $pos, $trm, $chk)
  322.                                # currently ignores $chk
  323.             my ( $obj, undef, undef, $pos, $trm ) = @_;
  324.             my ( $rdst, $rsrc, $rpos ) = \@_[ 1, 2, 3 ];
  325.             use bytes;
  326.             if ( ( my $npos = index( $$rsrc, $trm, $pos ) ) >= 0 ) {
  327.                 $$rdst .=
  328.                   substr( $$rsrc, $pos, $npos - $pos + length($trm) );
  329.                 $$rpos = $npos + length($trm);
  330.                 return 1;
  331.             }
  332.             $$rdst .= substr( $$rsrc, $pos );
  333.             $$rpos = length($$rsrc);
  334.             return '';
  335.         };
  336.         $Encode::Encoding{utf8} =
  337.           bless { Name => "utf8" } => "Encode::utf8";
  338.         $Encode::Encoding{"utf-8-strict"} =
  339.           bless { Name => "utf-8-strict", strict_utf8 => 1 } 
  340.             => "Encode::utf8";
  341.     }
  342. }
  343.  
  344. 1;
  345.  
  346. __END__
  347.  
  348. =head1 NAME
  349.  
  350. Encode - character encodings in Perl
  351.  
  352. =head1 SYNOPSIS
  353.  
  354.     use Encode;
  355.  
  356. =head2 Table of Contents
  357.  
  358. Encode consists of a collection of modules whose details are too extensive
  359. to fit in one document.  This one itself explains the top-level APIs
  360. and general topics at a glance.  For other topics and more details,
  361. see the documentation for these modules:
  362.  
  363.   Name                    Description
  364.   --------------------------------------------------------
  365.   Encode::Alias         Alias definitions to encodings
  366.   Encode::Encoding      Encode Implementation Base Class
  367.   Encode::Supported     List of Supported Encodings
  368.   Encode::CN            Simplified Chinese Encodings
  369.   Encode::JP            Japanese Encodings
  370.   Encode::KR            Korean Encodings
  371.   Encode::TW            Traditional Chinese Encodings
  372.   --------------------------------------------------------
  373.  
  374. =head1 DESCRIPTION
  375.  
  376. The C<Encode> module provides the interface between Perl strings
  377. and the rest of the system.  Perl strings are sequences of
  378. I<characters>.
  379.  
  380. The repertoire of characters that Perl can represent is a superset of those
  381. defined by the Unicode Consortium. On most platforms the ordinal
  382. values of a character as returned by C<ord(I<S>)> is the I<Unicode
  383. codepoint> for that character. The exceptions are platforms where
  384. the legacy encoding is some variant of EBCDIC rather than a superset
  385. of ASCII; see L<perlebcdic>.
  386.  
  387. During recent history, data is moved around a computer in 8-bit chunks,
  388. often called "bytes" but also known as "octets" in standards documents.
  389. Perl is widely used to manipulate data of many types: not only strings of
  390. characters representing human or computer languages, but also "binary"
  391. data, being the machine's representation of numbers, pixels in an image, or
  392. just about anything.
  393.  
  394. When Perl is processing "binary data", the programmer wants Perl to
  395. process "sequences of bytes". This is not a problem for Perl: because a
  396. byte has 256 possible values, it easily fits in Perl's much larger
  397. "logical character".
  398.  
  399. =head2 TERMINOLOGY
  400.  
  401. =over 2
  402.  
  403. =item *
  404.  
  405. I<character>: a character in the range 0 .. 2**32-1 (or more);
  406. what Perl's strings are made of.
  407.  
  408. =item *
  409.  
  410. I<byte>: a character in the range 0..255;
  411. A special case of a Perl character.
  412.  
  413. =item *
  414.  
  415. I<octet>: 8 bits of data, with ordinal values 0..255;
  416. Term for bytes passed to or from a non-Perl context, such as a disk file.
  417.  
  418. =back
  419.  
  420. =head1 THE PERL ENCODING API
  421.  
  422. =over 2
  423.  
  424. =item $octets  = encode(ENCODING, STRING[, CHECK])
  425.  
  426. Encodes the scalar value I<STRING> from Perl's internal form into
  427. I<ENCODING> and returns a sequence of octets.  I<ENCODING> can be either a
  428. canonical name or an alias.  For encoding names and aliases, see
  429. L</"Defining Aliases">.  For CHECK, see L</"Handling Malformed Data">.
  430.  
  431. For example, to convert a string from Perl's internal format into
  432. ISO-8859-1, also known as Latin1:
  433.  
  434.   $octets = encode("iso-8859-1", $string);
  435.  
  436. B<CAVEAT>: When you run C<$octets = encode("utf8", $string)>, then
  437. $octets I<might not be equal to> $string.  Though both contain the
  438. same data, the UTF8 flag for $octets is I<always> off.  When you
  439. encode anything, the UTF8 flag on the result is always off, even when it
  440. contains a completely valid utf8 string. See L</"The UTF8 flag"> below.
  441.  
  442. If the $string is C<undef>, then C<undef> is returned.
  443.  
  444. =item $string = decode(ENCODING, OCTETS[, CHECK])
  445.  
  446. This function returns the string that results from decoding the scalar
  447. value I<OCTETS>, assumed to be a sequence of octets in I<ENCODING>, into
  448. Perl's internal form.  The returns the resulting string.  As with encode(),
  449. I<ENCODING> can be either a canonical name or an alias. For encoding names
  450. and aliases, see L</"Defining Aliases">; for I<CHECK>, see L</"Handling
  451. Malformed Data">.
  452.  
  453. For example, to convert ISO-8859-1 data into a string in Perl's
  454. internal format:
  455.  
  456.   $string = decode("iso-8859-1", $octets);
  457.  
  458. B<CAVEAT>: When you run C<$string = decode("utf8", $octets)>, then $string
  459. I<might not be equal to> $octets.  Though both contain the same data, the
  460. UTF8 flag for $string is on unless $octets consists entirely of ASCII data
  461. on ASCII machines or EBCDIC on EBCDIC machines.  See L</"The UTF8 flag">
  462. below.
  463.  
  464. If the $string is C<undef>, then C<undef> is returned.
  465.  
  466. =item [$obj =] find_encoding(ENCODING)
  467.  
  468. Returns the I<encoding object> corresponding to I<ENCODING>.  Returns
  469. C<undef> if no matching I<ENCODING> is find.  The returned object is
  470. what does the actual encoding or decoding.
  471.  
  472.   $utf8 = decode($name, $bytes);
  473.  
  474. is in fact
  475.  
  476.     $utf8 = do {
  477.         $obj = find_encoding($name);
  478.         croak qq(encoding "$name" not found) unless ref $obj;
  479.         $obj->decode($bytes);
  480.     };
  481.  
  482. with more error checking.
  483.  
  484. You can therefore save time by reusing this object as follows;
  485.  
  486.     my $enc = find_encoding("iso-8859-1");
  487.     while(<>) {
  488.         my $utf8 = $enc->decode($_);
  489.         ... # now do something with $utf8;
  490.     }
  491.  
  492. Besides C<< ->decode >> and C<< ->encode >>, other methods are
  493. available as well.  For instance, C<< ->name >> returns the canonical
  494. name of the encoding object.
  495.  
  496.   find_encoding("latin1")->name; # iso-8859-1
  497.  
  498. See L<Encode::Encoding> for details.
  499.  
  500. =item [$length =] from_to($octets, FROM_ENC, TO_ENC [, CHECK])
  501.  
  502. Converts I<in-place> data between two encodings. The data in $octets
  503. must be encoded as octets and I<not> as characters in Perl's internal
  504. format. For example, to convert ISO-8859-1 data into Microsoft's CP1250
  505. encoding:
  506.  
  507.   from_to($octets, "iso-8859-1", "cp1250");
  508.  
  509. and to convert it back:
  510.  
  511.   from_to($octets, "cp1250", "iso-8859-1");
  512.  
  513. Because the conversion happens in place, the data to be
  514. converted cannot be a string constant: it must be a scalar variable.
  515.  
  516. from_to() returns the length of the converted string in octets on success,
  517. and C<undef> on error.
  518.  
  519. B<CAVEAT>: The following operations may look the same, but are not:
  520.  
  521.   from_to($data, "iso-8859-1", "utf8"); #1
  522.   $data = decode("iso-8859-1", $data);  #2
  523.  
  524. Both #1 and #2 make $data consist of a completely valid UTF-8 string,
  525. but only #2 turns the UTF8 flag on.  #1 is equivalent to:
  526.  
  527.   $data = encode("utf8", decode("iso-8859-1", $data));
  528.  
  529. See L</"The UTF8 flag"> below.
  530.  
  531. Also note that:
  532.  
  533.   from_to($octets, $from, $to, $check);
  534.  
  535. is equivalent t:o
  536.  
  537.   $octets = encode($to, decode($from, $octets), $check);
  538.  
  539. Yes, it does I<not> respect the $check during decoding.  It is
  540. deliberately done that way.  If you need minute control, use C<decode>
  541. followed by C<encode> as follows:
  542.  
  543.   $octets = encode($to, decode($from, $octets, $check_from), $check_to);
  544.  
  545. =item $octets = encode_utf8($string);
  546.  
  547. Equivalent to C<$octets = encode("utf8", $string)>.  The characters in
  548. $string are encoded in Perl's internal format, and the result is returned
  549. as a sequence of octets.  Because all possible characters in Perl have a
  550. (loose, not strict) UTF-8 representation, this function cannot fail.
  551.  
  552. =item $string = decode_utf8($octets [, CHECK]);
  553.  
  554. Equivalent to C<$string = decode("utf8", $octets [, CHECK])>.
  555. The sequence of octets represented by $octets is decoded
  556. from UTF-8 into a sequence of logical characters.
  557. Because not all sequences of octets are valid UTF-8,
  558. it is quite possible for this function to fail.
  559. For CHECK, see L</"Handling Malformed Data">.
  560.  
  561. =back
  562.  
  563. =head2 Listing available encodings
  564.  
  565.   use Encode;
  566.   @list = Encode->encodings();
  567.  
  568. Returns a list of canonical names of available encodings that have already
  569. been loaded.  To get a list of all available encodings including those that
  570. have not yet been loaded, say:
  571.  
  572.   @all_encodings = Encode->encodings(":all");
  573.  
  574. Or you can give the name of a specific module:
  575.  
  576.   @with_jp = Encode->encodings("Encode::JP");
  577.  
  578. When "C<::>" is not in the name, "C<Encode::>" is assumed.
  579.  
  580.   @ebcdic = Encode->encodings("EBCDIC");
  581.  
  582. To find out in detail which encodings are supported by this package,
  583. see L<Encode::Supported>.
  584.  
  585. =head2 Defining Aliases
  586.  
  587. To add a new alias to a given encoding, use:
  588.  
  589.   use Encode;
  590.   use Encode::Alias;
  591.   define_alias(NEWNAME => ENCODING);
  592.  
  593. After that, I<NEWNAME> can be used as an alias for I<ENCODING>.
  594. <ENCODING> may be either the name of an encoding or an
  595. I<encoding object>.
  596.  
  597. Before you do that, first make sure the alias is nonexistent using
  598. C<resolve_alias()>, which returns the canonical name thereof.
  599. For example:
  600.  
  601.   Encode::resolve_alias("latin1") eq "iso-8859-1" # true
  602.   Encode::resolve_alias("iso-8859-12")   # false; nonexistent
  603.   Encode::resolve_alias($name) eq $name  # true if $name is canonical
  604.  
  605. resolve_alias() does not need C<use Encode::Alias>; it can be
  606. imported via C<use Encode qw(resolve_alias)>.
  607.  
  608. See L<Encode::Alias> for details.
  609.  
  610. =head2 Finding IANA Character Set Registry names
  611.  
  612. The canonical name of a given encoding does not necessarily agree with
  613. IANA Character Set Registry, commonly seen as C<< Content-Type:
  614. text/plain; charset=I<WHATEVER> >>.  For most cases, the canonical name
  615. works, but sometimes it does not, most notably with "utf-8-strict".
  616.  
  617. As of C<Encode> version 2.21, a new method C<mime_name()> is thereforeadded.
  618.  
  619.   use Encode;
  620.   my $enc = find_encoding("UTF-8");
  621.   warn $enc->name;      # utf-8-strict
  622.   warn $enc->mime_name; # UTF-8
  623.  
  624. See also:  L<Encode::Encoding>
  625.  
  626. =head1 Encoding via PerlIO
  627.  
  628. If your perl supports C<PerlIO> (which is the default), you can use a
  629. C<PerlIO> layer to decode and encode directly via a filehandle.  The
  630. following two examples are fully identical in functionality:
  631.  
  632.   ### Version 1 via PerlIO
  633.     open(INPUT,  "< :encoding(shiftjis)", $infile)
  634.         || die "Can't open < $infile for reading: $!";
  635.     open(OUTPUT, "> :encoding(euc-jp)",  $outfile)
  636.         || die "Can't open > $output for writing: $!";
  637.     while (<INPUT>) {   # auto decodes $_
  638.         print OUTPUT;   # auto encodes $_
  639.     }
  640.     close(INPUT)   || die "can't close $infile: $!";
  641.     close(OUTPUT)  || die "can't close $outfile: $!";
  642.  
  643.   ### Version 2 via from_to()
  644.     open(INPUT,  "< :raw", $infile)
  645.         || die "Can't open < $infile for reading: $!";
  646.     open(OUTPUT, "> :raw",  $outfile)
  647.         || die "Can't open > $output for writing: $!";
  648.  
  649.     while (<INPUT>) {
  650.         from_to($_, "shiftjis", "euc-jp", 1);  # switch encoding
  651.         print OUTPUT;   # emit raw (but properly encoded) data
  652.     }
  653.     close(INPUT)   || die "can't close $infile: $!";
  654.     close(OUTPUT)  || die "can't close $outfile: $!";
  655.  
  656. In the first version above, you let the appropriate encoding layer
  657. handle the conversion.  In the second, you explicitly translate
  658. from one encoding to the other.
  659.  
  660. Unfortunately, it may be that encodings are C<PerlIO>-savvy.  You can check
  661. to see whether your encoding is supported by C<PerlIO> by invoking the
  662. C<perlio_ok> method on it:
  663.  
  664.   Encode::perlio_ok("hz");             # false
  665.   find_encoding("euc-cn")->perlio_ok;  # true wherever PerlIO is available
  666.  
  667.   use Encode qw(perlio_ok);            # imported upon request
  668.   perlio_ok("euc-jp")
  669.  
  670. Fortunately, all encodings that come with C<Encode> core are C<PerlIO>-savvy
  671. except for "hz" and "ISO-2022-kr".  For the gory details, see
  672. L<Encode::Encoding> and L<Encode::PerlIO>.
  673.  
  674. =head1 Handling Malformed Data
  675.  
  676. The optional I<CHECK> argument tells C<Encode> what to do when
  677. encountering malformed data.  Without I<CHECK>, C<Encode::FB_DEFAULT>
  678. (== 0) is assumed.
  679.  
  680. As of version 2.12, C<Encode> supports coderef values for C<CHECK>;
  681. see below.
  682.  
  683. =over 2
  684.  
  685. =item B<NOTE:> Not all encoding support this feature
  686.  
  687. Some encodings ignore I<CHECK> argument.  For example,
  688. L<Encode::Unicode> ignores I<CHECK> and it always croaks on error.
  689.  
  690. =back
  691.  
  692. Now here is the list of I<CHECK> values available
  693.  
  694. =over 2
  695.  
  696. =item I<CHECK> = Encode::FB_DEFAULT ( == 0)
  697.  
  698. If I<CHECK> is 0, encoding and decoding replace any malformed character
  699. with a I<substitution character>.  When you encode, I<SUBCHAR> is used.
  700. When you decode, the Unicode REPLACEMENT CHARACTER, code point U+FFFD, is
  701. used.  If the data is supposed to be UTF-8, an optional lexical warning of
  702. warning category C<"utf8"> is given.
  703.  
  704. =item I<CHECK> = Encode::FB_CROAK ( == 1)
  705.  
  706. If I<CHECK> is 1, methods immediately die with an error
  707. message.  Therefore, when I<CHECK> is 1, you should trap
  708. exceptions with C<eval{}>, unless you really want to let it C<die>.
  709.  
  710. =item I<CHECK> = Encode::FB_QUIET
  711.  
  712. If I<CHECK> is set to C<Encode::FB_QUIET>, encoding and decoding immediately
  713. return the portion of the data that has been processed so far when an
  714. error occurs. The data argument is overwritten with everything
  715. after that point; that is, the unprocessed portion of the data.  This is
  716. handy when you have to call C<decode> repeatedly in the case where your
  717. source data may contain partial multi-byte character sequences,
  718. (that is, you are reading with a fixed-width buffer). Here's some sample
  719. code to do exactly that:
  720.  
  721.     my($buffer, $string) = ("", "");
  722.     while (read($fh, $buffer, 256, length($buffer))) {
  723.         $string .= decode($encoding, $buffer, Encode::FB_QUIET);
  724.         # $buffer now contains the unprocessed partial character
  725.     }
  726.  
  727. =item I<CHECK> = Encode::FB_WARN
  728.  
  729. This is the same as C<FB_QUIET> above, except that instead of being silent
  730. on errors, it issues a warning.  This is handy for when you are debugging.
  731.  
  732. =item perlqq mode (I<CHECK> = Encode::FB_PERLQQ)
  733.  
  734. =item HTML charref mode (I<CHECK> = Encode::FB_HTMLCREF)
  735.  
  736. =item XML charref mode (I<CHECK> = Encode::FB_XMLCREF)
  737.  
  738. For encodings that are implemented by the C<Encode::XS> module, C<CHECK> C<==>
  739. C<Encode::FB_PERLQQ> puts C<encode> and C<decode> into C<perlqq> fallback mode.
  740.  
  741. When you decode, C<\xI<HH>> is inserted for a malformed character, where
  742. I<HH> is the hex representation of the octet that could not be decoded to
  743. utf8.  When you encode, C<\x{I<HHHH>}> will be inserted, where I<HHHH> is
  744. the Unicode code point (in any number of hex digits) of the character that
  745. cannot be found in the character repertoire of the encoding.
  746.  
  747. The HTML/XML character reference modes are about the same. In place of
  748. C<\x{I<HHHH>}>, HTML uses C<&#I<NNN>;> where I<NNN> is a decimal number, and
  749. XML uses C<&#xI<HHHH>;> where I<HHHH> is the hexadecimal number.
  750.  
  751. In C<Encode> 2.10 or later, C<LEAVE_SRC> is also implied.
  752.  
  753. =item The bitmask
  754.  
  755. These modes are all actually set via a bitmask.  Here is how the C<FB_I<XXX>>
  756. constants are laid out.  You can import the C<FB_I<XXX>> constants via
  757. C<use Encode qw(:fallbacks)>, and you can import the generic bitmask
  758. constants via C<use Encode qw(:fallback_all)>.
  759.  
  760.                      FB_DEFAULT FB_CROAK FB_QUIET FB_WARN  FB_PERLQQ
  761.  DIE_ON_ERR    0x0001             X
  762.  WARN_ON_ERR   0x0002                               X
  763.  RETURN_ON_ERR 0x0004                      X        X
  764.  LEAVE_SRC     0x0008                                        X
  765.  PERLQQ        0x0100                                        X
  766.  HTMLCREF      0x0200
  767.  XMLCREF       0x0400
  768.  
  769. =back
  770.  
  771. =over 2
  772.  
  773. =item Encode::LEAVE_SRC
  774.  
  775. If the C<Encode::LEAVE_SRC> bit is I<not> set but I<CHECK> is set, then the
  776. second argument to encode() or decode() will be overwritten in place.
  777. If you're not interested in this, then bitwise-OR it with the bitmask.
  778.  
  779. =back
  780.  
  781. =head2 coderef for CHECK
  782.  
  783. As of C<Encode> 2.12, C<CHECK> can also be a code reference which takes the
  784. ordinal value of the unmapped caharacter as an argument and returns a string
  785. that represents the fallback character.  For instance:
  786.  
  787.   $ascii = encode("ascii", $utf8, sub{ sprintf "<U+%04X>", shift });
  788.  
  789. Acts like C<FB_PERLQQ> but U+I<XXXX> is used instead of C<\x{I<XXXX>}>.
  790.  
  791. =head1 Defining Encodings
  792.  
  793. To define a new encoding, use:
  794.  
  795.     use Encode qw(define_encoding);
  796.     define_encoding($object, CANONICAL_NAME [, alias...]);
  797.  
  798. I<CANONICAL_NAME> will be associated with I<$object>.  The object
  799. should provide the interface described in L<Encode::Encoding>.
  800. If more than two arguments are provided, additional
  801. arguments are considered aliases for I<$object>.
  802.  
  803. See L<Encode::Encoding> for details.
  804.  
  805. =head1 The UTF8 flag
  806.  
  807. Before the introduction of Unicode support in Perl, The C<eq> operator
  808. just compared the strings represented by two scalars. Beginning with
  809. Perl 5.8, C<eq> compares two strings with simultaneous consideration of
  810. I<the UTF8 flag>. To explain why we made it so, I quote from page 402 of
  811. I<Programming Perl, 3rd ed.>
  812.  
  813. =over 2
  814.  
  815. =item Goal #1:
  816.  
  817. Old byte-oriented programs should not spontaneously break on the old
  818. byte-oriented data they used to work on.
  819.  
  820. =item Goal #2:
  821.  
  822. Old byte-oriented programs should magically start working on the new
  823. character-oriented data when appropriate.
  824.  
  825. =item Goal #3:
  826.  
  827. Programs should run just as fast in the new character-oriented mode
  828. as in the old byte-oriented mode.
  829.  
  830. =item Goal #4:
  831.  
  832. Perl should remain one language, rather than forking into a
  833. byte-oriented Perl and a character-oriented Perl.
  834.  
  835. =back
  836.  
  837. When I<Programming Perl, 3rd ed.> was written, not even Perl 5.6.0 had been
  838. born yet, many features documented in the book remained unimplemented for a
  839. long time.  Perl 5.8 corrected much of this, and the introduction of the
  840. UTF8 flag is one of them.  You can think of there being two fundamentally
  841. different kinds of strings and string-operations in Perl: one a
  842. byte-oriented mode  for when the internal UTF8 flag is off, and the other a
  843. character-oriented mode for when the internal UTF8 flag is on.
  844.  
  845. Here is how C<Encode> handles the UTF8 flag.
  846.  
  847. =over 2
  848.  
  849. =item *
  850.  
  851. When you I<encode>, the resulting UTF8 flag is always B<off>.
  852.  
  853. =item *
  854.  
  855. When you I<decode>, the resulting UTF8 flag is B<on>--I<unless> you can
  856. unambiguously represent data.  Here is what we mean by "unambiguously".
  857. After C<$utf8 = decode("foo", $octet)>,
  858.  
  859.   When $octet is...   The UTF8 flag in $utf8 is
  860.   ---------------------------------------------
  861.   In ASCII only (or EBCDIC only)            OFF
  862.   In ISO-8859-1                              ON
  863.   In any other Encoding                      ON
  864.   ---------------------------------------------
  865.  
  866. As you see, there is one exception: in ASCII.  That way you can assume
  867. Goal #1.  And with C<Encode>, Goal #2 is assumed but you still have to be
  868. careful in the cases mentioned in the B<CAVEAT> paragraphs above.
  869.  
  870. This UTF8 flag is not visible in Perl scripts, exactly for the same reason
  871. you cannot (or rather, you I<don't have to>) see whether a scalar contains
  872. a string, an integer, or a floating-point number.   But you can still peek
  873. and poke these if you will.  See the next section.
  874.  
  875. =back
  876.  
  877. =head2 Messing with Perl's Internals
  878.  
  879. The following API uses parts of Perl's internals in the current
  880. implementation.  As such, they are efficient but may change in a future
  881. release.
  882.  
  883. =over 2
  884.  
  885. =item is_utf8(STRING [, CHECK])
  886.  
  887. [INTERNAL] Tests whether the UTF8 flag is turned on in the I<STRING>.
  888. If I<CHECK> is true, also checks whether I<STRING> contains well-formed
  889. UTF-8.  Returns true if successful, false otherwise.
  890.  
  891. As of Perl 5.8.1, L<utf8> also has the C<utf8::is_utf8> function.
  892.  
  893. =item _utf8_on(STRING)
  894.  
  895. [INTERNAL] Turns the I<STRING>'s internal UTF8 flag B<on>.  The I<STRING>
  896. is I<not> checked for containing only well-formed UTF-8.  Do not use this
  897. unless you I<know with absolute certainty> that the STRING holds only
  898. well-formed UTF-8.  Returns the previous state of the UTF8 flag (so please
  899. don't treat the return value as indicating success or failure), or C<undef>
  900. if I<STRING> is not a string.
  901.  
  902. B<NOTE>: For security reasons, this function does not work on tainted values.
  903.  
  904. =item _utf8_off(STRING)
  905.  
  906. [INTERNAL] Turns the I<STRING>'s internal UTF8 flag B<off>.  Do not use
  907. frivolously.  Returns the previous state of the UTF8 flag, or C<undef> if
  908. I<STRING> is not a string.  Do not treat the return value as indicative of
  909. success or failure, because that isn't what it means: it is only the
  910. previous setting.
  911.  
  912. B<NOTE>: For security reasons, this function does not work on tainted values.
  913.  
  914. =back
  915.  
  916. =head1 UTF-8 vs. utf8 vs. UTF8
  917.  
  918.   ....We now view strings not as sequences of bytes, but as sequences
  919.   of numbers in the range 0 .. 2**32-1 (or in the case of 64-bit
  920.   computers, 0 .. 2**64-1) -- Programming Perl, 3rd ed.
  921.  
  922. That has historically been Perl's notion of UTF-8, as that is how UTF-8 was
  923. first conceived by Ken Thompson when he invented it. However, thanks to
  924. later revisions to the applicable standards, official UTF-8 is now rather
  925. stricter than that. For example, its range is much narrower (0 .. 0x10_FFFF
  926. to cover only 21 bits instead of 32 or 64 bits) and some sequences
  927. are not allowed, like those used in surrogate pairs, the 31 non-character
  928. code points 0xFDD0 .. 0xFDEF, the last two code points in I<any> plane
  929. (0xI<XX>_FFFE and 0xI<XX>_FFFF), all non-shortest encodings, etc.
  930.  
  931. The former default in which Perl would always use a loose interpretation of
  932. UTF-8 has now been overruled:
  933.  
  934.   From: Larry Wall <larry@wall.org>
  935.   Date: December 04, 2004 11:51:58 JST
  936.   To: perl-unicode@perl.org
  937.   Subject: Re: Make Encode.pm support the real UTF-8
  938.   Message-Id: <20041204025158.GA28754@wall.org>
  939.  
  940.   On Fri, Dec 03, 2004 at 10:12:12PM +0000, Tim Bunce wrote:
  941.   : I've no problem with 'utf8' being perl's unrestricted uft8 encoding,
  942.   : but "UTF-8" is the name of the standard and should give the
  943.   : corresponding behaviour.
  944.  
  945.   For what it's worth, that's how I've always kept them straight in my
  946.   head.
  947.  
  948.   Also for what it's worth, Perl 6 will mostly default to strict but
  949.   make it easy to switch back to lax.
  950.  
  951.   Larry
  952.  
  953. Got that?  As of Perl 5.8.7, B<"UTF-8"> means UTF-8 in its current
  954. sense, which is conservative and strict and security-conscious, whereas
  955. B<"utf8"> means UTF-8 in its former sense, which was liberal and loose and
  956. lax.  C<Encode> version 2.10 or later thus groks this subtle but critically
  957. important distinction between C<"UTF-8"> and C<"utf8">.
  958.  
  959.   encode("utf8",  "\x{FFFF_FFFF}", 1); # okay
  960.   encode("UTF-8", "\x{FFFF_FFFF}", 1); # croaks
  961.  
  962. In the C<Encode> module, C<"UTF-8"> is actually a canonical name for
  963. C<"utf-8-strict">.  That hyphen between the C<"UTF"> and the C<"8"> is
  964. critical; without it, C<Encode> goes "liberal" and (perhaps overly-)permissive:
  965.  
  966.   find_encoding("UTF-8")->name # is 'utf-8-strict'
  967.   find_encoding("utf-8")->name # ditto. names are case insensitive
  968.   find_encoding("utf_8")->name # ditto. "_" are treated as "-"
  969.   find_encoding("UTF8")->name  # is 'utf8'.
  970.  
  971. Perl's internal UTF8 flag is called "UTF8", without a hyphen. It indicates
  972. whether a string is internally encoded as "utf8", also without a hyphen.
  973.  
  974. =head1 SEE ALSO
  975.  
  976. L<Encode::Encoding>,
  977. L<Encode::Supported>,
  978. L<Encode::PerlIO>,
  979. L<encoding>,
  980. L<perlebcdic>,
  981. L<perlfunc/open>,
  982. L<perlunicode>, L<perluniintro>, L<perlunifaq>, L<perlunitut>
  983. L<utf8>,
  984. the Perl Unicode Mailing List E<lt>perl-unicode@perl.orgE<gt>
  985.  
  986. =head1 MAINTAINER
  987.  
  988. This project was originated by the late Nick Ing-Simmons and later
  989. maintained by Dan Kogai I<< <dankogai@dan.co.jp> >>.  See AUTHORS
  990. for a full list of people involved.  For any questions, send mail to
  991. I<< <perl-unicode@perl.org> >> so that we can all share.
  992.  
  993. While Dan Kogai retains the copyright as a maintainer, credit
  994. should go to all those involved.  See AUTHORS for a list of those
  995. who submitted code to the project.
  996.  
  997. =head1 COPYRIGHT
  998.  
  999. Copyright 2002-2011 Dan Kogai I<< <dankogai@dan.co.jp> >>.
  1000.  
  1001. This library is free software; you can redistribute it and/or modify
  1002. it under the same terms as Perl itself.
  1003.  
  1004. =cut
  1005.